/**
 *	Management Console
 */
"user strict"

module.exports 			= function(app, settings){
	var log4js 				= require('log4js')
		, debug					= require('debug')('console')
		, util 					= require('util')
		, csrf 					= require('csurf') // ref: https://github.com/expressjs/csurf
		, cls 					= require('../../libs/continuationLocalStorage')
		, cookieParser 	= require('cookie-parser')
		, cookiee 			= require("cookie-encryption")
		, jwt          	= require("jsonwebtoken")
		, url 					= require('url')
		, models 				= require('../../models'); //Use this npm in the future TODO: replace nJwt

	var ADMIN_COOKIE_NAME			= settings.adminCookieName 		= 'sutk'
		, ADMIN_COOKIE_SECRET 	= settings.adminCookieSecret 	= 'theC00kieOf$uperu$ers'
		, ADMIN_JWT_SECRET  		= settings.adminJwtSecret 		= '98d29f11-1b87-4b78-bb82-6ece6cbeda23'
		, ADMIN_COOKIE_OPTIONS 	= settings.adminCookieOptions = {
				cookie: ADMIN_COOKIE_NAME
				,	maxAge: 7200
				, secure: false
				, cipher: 'aes-256-cbc'
				, encoding: 'base64'
				, httpOnly: true
				, signed: true
		};

	app.use(cookieParser(settings.adminCookieSecret, settings.adminCookieOptions));

	var logger 		= log4js.getLogger("console")
		, namespace = cls.createNamespace()
		, csrfProtection = csrf({ cookie: true });

	//set template location
	app.set('views', './routes/console/views');

	require('./oauth2')(app, settings);

	/**
	 *	Login page does not require authentication
	 */
	app.route("/login", function(req, res, next){
		return next();
	})
	.get(csrfProtection, function(req, res, next){
		return res.render("login", { _csrf: req.csrfToken() });
	});

	/**
	 * TODO: Should check if the token expires and refresh the token
	 *  So a refresh token may also be set in user agent's cookie
	 */
	var validateBearerToken = function(token, cb){
		var verifiedJwt = jwt.verify(token, settings.adminJwtSecret
									, { algorithms: ['RS256', 'HS256'] }
									, function(err, token){
			if(err){
				// respond to request with error
				debug("JWT Token Vefication Error: ", err);
				return cb(err);
			}else{
				// continue with the request
				// return deseriazlied JWT token
				return cb(null, token);
			}
		});
	}

	app.use(function(req, res, next){
	  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
	  debug('Client IP:', ip);

	  //Read jwtToken from cookie  or from authorization Bearer head
	  var token = req.signedCookies[settings.adminCookieName];
	  debug("signed token cookie:", token);
	  if(!token){
	    //validate user JWT token and permissions
	    var bearer = req.headers['authorization'];
	    debug("Authorization: " + bearer);
	    if(bearer){
	      token = bearer.substring("Bearer".length).trim();
	    }
	  }

	  validateBearerToken(token, function(err, verified){
	    if(err){
	      if(req.originalUrl.toLowerCase().indexOf('/console') === 0){
	        //redirect to login page w/ returnUrl
	        var returnUrl = url.format({
	            protocol: req.get('X-Forwarded-Proto') || req.protocol,
	            host: req.get('host'),
	            pathname: req.originalUrl
	        });

	        debug("Return URL: ", returnUrl );

	        return res.redirect('/console/login?returnUrl=' + returnUrl);
	      }else{
	        return res.status(401).json({
	          success: false
	          , message: 'UnAuthorized'
	        });
	      }
	    }

	    res.locals.userToken = verified;
	    return next();
	  });
	});



	//account subapp handle all frontend authentication requests
	app.get('/', function(req, res, next){
	    debug("admin console home page");
			return res.render('index');
	});

	require('./accounts')(app, settings);
	require('./users')(app, settings);
	require('./administrators')(app, settings);

}
